
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>客户需求</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
    <link rel="stylesheet" href="${re.contextPath}/plugin/layui/css/layui.css">
    <script type="text/javascript" src="${re.contextPath}/plugin/jquery/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="${re.contextPath}/plugin/layui/layui.all.js" charset="utf-8"></script>
    <script type="text/javascript" src="${re.contextPath}/plugin/tools/tool.js"></script>
    <meta charset="utf-8" />
    <meta name="renderer" content="webkit" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="format-detection" content="telephone=no" />
    <title>Layui表格添加行删除保存代码 - 站长素材</title>

    <link rel="stylesheet" href="layui/css/layui.css" />
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style type="text/css">
        /*您可以将下列样式写入自己的样式表中*/
        .childBody{padding: 15px;}

        /*layui 元素样式改写*/
        .layui-btn-sm{line-height: normal; font-size: 12.5px;}
        .layui-table-view .layui-table-body{min-height: 256px;}
        .layui-table-cell .layui-input.layui-unselect{height: 30px; line-height: 30px;}

        /*设置 layui 表格中单元格内容溢出可见样式*/
        .table-overlay .layui-table-view,
        .table-overlay .layui-table-box,
        .table-overlay .layui-table-body{overflow: visible;}
        .table-overlay .layui-table-cell{height: auto; overflow: visible;}

        /*文本对齐方式*/
        .text-center{text-align: center;}
    </style>

</head>

<body class="childBody">
<form class="layui-form layui-form-pane" id="saveForm" style="margin-left: 20px;">
    <div class="layui-input-inline">
        <button type="button" class="layui-btn" id="test3"><i class="layui-icon"></i>上传文件</button>
    </div>
    <div class="layui-form-item">
        <div class="layui-inline">
            <label for="realName" class="layui-form-label">
                <span class="x-red">*</span>编号
            </label>
            <div class="layui-input-inline">
                <input type="text" id="orderNo" value="${demand.orderNo}" disabled="disabled" name="orderNo" lay-verify="weight"  autocomplete="off" class="layui-input">
                <input type="hidden" id="id" value="${demand.id}" name="id" lay-verify="weight"  autocomplete="off" class="layui-input">
            </div>
        </div>
<#--        <div class="layui-inline">-->
<#--            <label for="realName" class="layui-form-label">-->
<#--                <span class="x-red">*</span>重量-->
<#--            </label>-->
<#--            <div class="layui-input-inline">-->
<#--                <input type="text" id="weight" value="${demand.weight}" name="weight" lay-verify="weight"  autocomplete="off" class="layui-input">-->
<#--            </div>-->
<#--        </div>-->
<#--        <div class="layui-inline">-->
<#--            <label for="realName" class="layui-form-label">-->
<#--                <span class="x-red">*</span>工期-->
<#--            </label>-->
<#--            <div class="layui-input-inline">-->
<#--                <input type="text" id="period" value="${demand.period}" name="period" lay-verify="period"  autocomplete="off" class="layui-input">-->
<#--            </div>-->
<#--        </div>-->
<#--        <div class="layui-inline">-->
<#--            <label for="realName" class="layui-form-label">-->
<#--                <span class="x-red">*</span>外协打印（含税、含运费）-->
<#--            </label>-->
<#--            <div class="layui-input-inline">-->
<#--                <input type="text" id="foreignPrient" value="${demand.foreignPrient}" name="foreignPrient" lay-verify="saleName"  autocomplete="off" class="layui-input">-->
<#--            </div>-->
<#--        </div>-->
<#--        <div class="layui-inline">-->
<#--            <label for="realName" class="layui-form-label">-->
<#--                <span class="x-red">*</span>外协后处理（含税、含运费）-->
<#--            </label>-->
<#--            <div class="layui-input-inline">-->
<#--                <input type="text" id="foreignHandle" value="${demand.foreignHandle}" name="foreignHandle" lay-verify="saleName"  autocomplete="off" class="layui-input">-->
<#--            </div>-->
<#--        </div>-->
        <div class="layui-inline">
            <label for="realName" class="layui-form-label">
                <span class="x-red">*</span>收货信息
            </label>
            <div class="layui-input-inline">
                <input type="text" id="receiving" value="${demand.receiving}" name="receiving" lay-verify="saleName"  autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <div class="layui-inline">
        <label for="age" class="layui-form-label">
            <span class="x-red"></span>文件
        </label>
        <div class="layui-input-inline">
            <div class="layui-input-inline">
                <input type="text"  id="file" name="file" onclick="danji()" value="${demand.file}" lay-verify="file"
                       autocomplete="off" class="layui-input">
            </div>
        </div>
    </div>
    <section class="layui-col-md10" style="margin: 0 auto; float: none;">
        <div class="layui-card">
            <div class="layui-card-body layui-text">
                <div id="tableRes" class="table-overlay">
                    <table id="dataTable" lay-filter="dataTable" class="layui-hide"></table>
                </div>
                <div id="action" class="text-center">
                    <button type="button" name="btnSave" class="layui-btn" data-type="save"><i class="layui-icon layui-icon-ok-circle"></i>保存</button>
                    <button  class="layui-btn"  lay-filter="trans" lay-submit >
                        生成报价单
                    </button>
                    <button  class="layui-btn"  lay-filter="down" lay-submit >
                        下载
                    </button>
                    <button type="reset" name="btnReset" class="layui-btn layui-btn-primary">取消</button>
                </div>
            </div>
        </div>

    </section>
</form>
<!--recommended script position-->
<script src="layui/layui.js?v=201805080202" charset="utf-8"></script>
<script type="text/javascript">
    //准备视图对象
    window.viewObj = {
        tbData: [{
            sample: '1',
            design: '1',
            material: '1',
            technology: '1',
            handle: '1',
            number: '1'

        }],
        typeData: [
            {id: 1, name: '分类一'},
            {id: 2, name: '分类二'},
            {id: 3, name: '分类三'},
            {id: 4, name: '分类四'}
        ],
        renderSelectOptions: function(data, settings){
            settings =  settings || {};
            var valueField = settings.valueField || 'value',
                textField = settings.textField || 'text',
                selectedValue = settings.selectedValue || "";
            var html = [];
            for(var i=0, item; i < data.length; i++){
                item = data[i];
                html.push('<option value="');
                html.push(item[valueField]);
                html.push('"');
                if(selectedValue && item[valueField] == selectedValue ){
                    html.push(' selected="selected"');
                }
                html.push('>');
                html.push(item[textField]);
                html.push('</option>');
            }
            return html.join('');
        }
    };
    function serializeRemoveNull(serStr){
        return serStr.split("&").filter(str => !str.endsWith("=")).join("&");
    }
    function danji() {
        var photos = $("#file").val();
        // document.write(location.href);
        window.open('/images/'+photos,'','');
    }
    function sub() {
        var dataFrom = serializeRemoveNull($("#saveForm").serialize());
        var tableData= JSON.stringify(table.cache[layTableId]);
        console.log(addTime);
        $.ajax({
            url: "addDemand",
            type: "post",
            data:JSON.parse(dataFrom),
            success: function (data) {
                window.top.layer.msg("保存成功", {icon: 6, offset: 'rb', area: ['120px', '80px'], anim: 2});
                window.parent.location.reload();//刷新父页面
                var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                parent.layer.close(index);
            },
            error: function () {
                alert("保存失败");
            }
        })
    }
    function checkC(){
        var order = $("#orderNo").val();
        if(order ==""){
            alert("编号不能为空");
            return false;
        }

        return true;
    }
    function serializeToObject(jsonArray){
        var o = {};
        $.each(jsonArray, function() {
            if (o[this.name] !== undefined) {
                if(o[this.name] !== 'LAY_TABLE_INDEX') {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                }
            } else {
                o[this.name] = this.value || '';
            }
            // delete o.LAY_TABLE_INDEX;
        });
        return o;
    }

    //layui 模块化引用
    layui.use(['jquery', 'table', 'layer','form','upload'], function(){
        var $ = layui.$, table = layui.table, form = layui.form, upload = layui.upload, layer = layui.layer;
        upload.render({
            elem: '#test3'
            ,url: 'upload'
            ,accept: 'file',
            before: function(obj){
                //预读，不支持ie8
                obj.preview(function(index, file, result){
                    $('#demo2').find('img').remove();
                    $('#demo2').append('<span class="x-red">已经上传</span>');
                });
            },done: function(res){
                if(!res.flag){
                    layer.msg(res.msg,{icon: 5,anim: 6});
                }else{
                    console.log(res);
                    $("#file").val(res.msg);
                    console.info($('#file').val());
                }
            }
        });
        //数据表格实例化
        var tbWidth = $("#tableRes").width();
        var order = $('#orderNo').val();
        var layTableId = "layTable";
        var tableIns = table.render({
            elem: '#dataTable',
            id: layTableId,
            data: viewObj.tbData,
            width: tbWidth,
            url : 'showProductDemand?id='+order,
            page: true,
            loading: false,
            even: false, //不开启隔行背景
            cols: [[
                // {title: '序号', type: 'numbers'},
                {field: 'sample', title: '样件名称', edit: 'text'},
                {field: 'design', title: '设计类型', edit: 'text'},
                {field: 'material', title: '材料类型', edit: 'text'},
                {field: 'technology', title: '工艺类型', edit: 'text'},
                {field: 'handle', title: '后处理要求', edit: 'text'},
                {field: 'number', title: '数量', edit: 'text'},
                {field: 'weight', title: '重量', edit: 'text',style:"background:red;"},
                {field: 'period', title: '工期', edit: 'text',style:"background:red;"},
                {field: 'foreignPrient', title: '外协打印', edit: 'text',style:"background-color:red;"},
                {field: 'foreignHandle', title: '外协处理', edit: 'text',style:"background:red;"}
                // {field: 'tempId', title: '操作', templet: function(d){
                //     return '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del" lay-id="'+ d.tempId +'"><i class="layui-icon layui-icon-delete"></i>移除</a>';
                //   }}
            ]],
            done: function(res, curr, count){
                viewObj.tbData = res.data;
            }
        });

        //定义事件集合
        var active = {
            addRow: function(){	//添加一行
                var oldData = table.cache[layTableId];

                var newRow = {id:'1',orderNo:order,sample: '1', design: '1', material: '1', technology: '1',handle: '1',number: '1'};
                oldData.push(newRow);
                console.log(oldData);
                tableIns.reload('dataTable',{
                    data : oldData
                });
            },
            updateRow: function(obj){
                var oldData = table.cache[layTableId];
                console.log(oldData);
                for(var i=0, row; i < oldData.length; i++){
                    row = oldData[i];
                    if(row.tempId == obj.tempId){
                        $.extend(oldData[i], obj);
                        return;
                    }
                }
                tableIns.reload({
                    data : oldData
                });
            },
            removeEmptyTableCache: function(){
                var oldData = table.cache[layTableId];
                for(var i=0, row; i < oldData.length; i++){
                    row = oldData[i];
                    if(!row || !row.tempId){
                        oldData.splice(i, 1);    //删除一项
                    }
                    continue;
                }
                tableIns.reload({
                    data : oldData
                });
            },
            save: function(){
                if(checkC() == false){
                    return;
                }
                var dataFrom = $("#saveForm").serializeArray();
                var jjj = serializeToObject(dataFrom);

                var taskDetails= JSON.stringify(table.cache[layTableId]);
                jjj.taskDetails = taskDetails;

                var eee = JSON.stringify(jjj);
                $.ajax({
                    url: "updateDemand",
                    type: "post",
                    dataType:'json',
                    contentType: "application/json",
                    async:false, traditional: true,
                    data:eee,
                    success: function (data) {
                        window.top.layer.msg("保存成功", {icon: 6, offset: 'rb', area: ['120px', '80px'], anim: 2});
                        window.parent.location.reload();//刷新父页面
                        var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                        parent.layer.close(index);
                    },
                    error: function () {
                        alert("保存失败");
                    }
                })
            }
        }
        //自定义验证规则
        form.verify({
            orderNo: function(value){
                if(value.trim()==""){
                    return "编号不能为空";
                }
            }
        });
        form.on('submit(down)', function (obj) {
            var data = $("#id").val();
            var orderNo = $("#orderNo").val();
            //console.log(obj)
            // 获取XMLHttpRequest
            var xmlResquest = new XMLHttpRequest();
            //  发起请求
            xmlResquest.open("POST", "download?id="+data, true);
            // 设置请求头类型
            xmlResquest.setRequestHeader("Content-type", "application/json");
            // xmlResquest.setRequestHeader("id",data.id);
            xmlResquest.responseType = "blob";
            //  返回
            xmlResquest.onload = function(oEvent) {
                //alert(this.status);
                var content = xmlResquest.response;
                // 组装a标签
                var elink = document.createElement("a");

                //获取文件格式,截取文件后缀
                // var fileaddr = data.fileAddress;
                // var index = fileaddr.lastIndexOf(".");
                // var length  =fileaddr.length;
                // var laterName = fileaddr.substring(index,length);
                //拼接下载的文件名
                // var newFileName = data.fileName+laterName;
                var newFileName = orderNo+'需求单.xls';
                //设置文件下载路径
                elink.download = newFileName;
                elink.style.display = "none";
                var blob = new Blob([content]);

                //解决下载不存在文件的问题，根据blob大小判断
                if(blob.size==0){
                    layer.msg('服务器没找到此文件，请联系管理员!');
                }else{
                    elink.href = URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }
            };
            xmlResquest.send();
        });
        form.on('submit(trans)', function(data){
            var da = $("#id").val();
            layer.msg(JSON.stringify(data.field));
            $.ajax({
                url:'trans',
                type:'post',
                dataType: "json",
                data:{id:da},
                async:false, traditional: true,
                success:function(d){
                    var index = parent.layer.getFrameIndex(window.name);
                    if(d.flag){
                        parent.layer.close(index);
                        window.parent.layui.table.reload('leaveList');
                        window.top.layer.msg(d.msg,{icon:6,offset: 'rb',area:['120px','80px'],anim:2});
                    }else{
                        layer.msg(d.msg,{icon:5});
                    }
                },error:function(){
                    layer.alert("请求失败", {icon: 6},function () {
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    });
                }
            });
            return false;
        });
        //激活事件
        var activeByType = function (type, arg) {
            if(arguments.length === 2){
                active[type] ? active[type].call(this, arg) : '';
            }else{
                active[type] ? active[type].call(this) : '';
            }
        }

        //注册按钮事件
        $('.layui-btn[data-type]').on('click', function () {
            var type = $(this).data('type');
            activeByType(type);
        });

        //监听select下拉选中事件
        form.on('select(type)', function(data){
            var elem = data.elem; //得到select原始DOM对象
            $(elem).prev("a[lay-event='type']").trigger("click");
        });

        //监听工具条
        table.on('tool(dataTable)', function (obj) {
            var data = obj.data, event = obj.event, tr = obj.tr; //获得当前行 tr 的DOM对象;
            console.log(data);
            switch(event){
                case "type":
                    //console.log(data);
                    var select = tr.find("select[name='type']");
                    if(select){
                        var selectedVal = select.val();
                        if(!selectedVal){
                            layer.tips("请选择一个分类", select.next('.layui-form-select'), { tips: [3, '#FF5722'] }); //吸附提示
                        }
                        console.log(selectedVal);
                        $.extend(obj.data, {'type': selectedVal});
                        activeByType('updateRow', obj.data);	//更新行记录对象
                    }
                    break;
                case "state":
                    var stateVal = tr.find("input[name='state']").prop('checked') ? 1 : 0;
                    $.extend(obj.data, {'state': stateVal})
                    activeByType('updateRow', obj.data);	//更新行记录对象
                    break;
                case "del":
                    layer.confirm('真的删除行么？', function(index){
                        obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                        layer.close(index);
                        activeByType('removeEmptyTableCache');
                    });
                    break;
            }
        });
    });
</script>

</body>

</html>
